import { Control, ControlProps } from '../common';
import { ShoppingService } from 'user/services/shoppingService';
import React = require('react');
import { ImageService } from 'maishu-services-sdk';


let DataListContext = React.createContext({ item: null })

class DataList extends React.Component<{ loadData: () => Promise<any[]>, className?: string }, { items: any[] }>{
    constructor(props) {
        super(props);
        this.state = { items: null };
    }

    async componentDidMount() {
        let items = await this.props.loadData();
        this.setState({ items })
    }

    async componentWillReceiveProps() {
        let items = await this.props.loadData();
        this.setState({ items })
    }

    render() {
        let items = this.state.items;
        if (items == null)
            return <div className="loading">
                <i className="icon-spinner icon-spin" style={{ marginRight: 4 }} />
                <span>数据正在加载中</span>
            </div>

        if (items.length == 0)
            return <div className="empty">暂无数据</div>

        return <div className={this.props.className}>
            {items.map((p, i) => <React.Fragment key={p.id || p.Id || i}>
                <DataListContext.Provider value={{ item: p }}>
                    {this.props.children}
                </DataListContext.Provider>
            </React.Fragment>)}
        </div>
    }
}

export interface Props extends ControlProps<DoubleColunmControl> {
    // createService<T extends chitu.Service>(type: chitu.ServiceConstructor<T>): T;
}

export interface State {
    // products?: Product[],
    // productsType?: ProductsFromCategory | ProductsByCustom,

    //=======================================
    productSourceType: 'category' | 'custom',
    //=======================================
    // 按类别
    categoryId?: string,
    //=======================================
    // 自定义
    productIds?: string[],
    //=======================================

    /**
     * 列表类型
     */
    listType: 'singleColumn' | 'doubleColumn' | 'largePicture',

    /**
     * 价格右侧显示内容类型
     */
    displayType?: 'none' | 'addProduct' | 'activity',

    // shoppingCartItems: ShoppingCartItem[],
    imageSize: 'small' | 'medium' | 'large',

    productsCount?: number,

    /**
     * 购买商品数量，用于购物车按钮
     */
    // productCounts?: { [key: string]: number },

    /**
     * 商品名称行数
     */
    productNameLines: 'singleLine' | 'doubleColumn',

    /**
     * 是否显示规格型号
     * independent 独立显示商品规格
     * append 将商品规格追加到名称后
     */
    showFields: 'independent' | 'append',

    /**
     * 商品模板
     */
    productTemplate?: string,

    products?: Product[],
}

export default class DoubleColunmControl extends Control<Props, State>  {
    private shoppingService: ShoppingService;
    imageService: ImageService;

    constructor(props) {
        super(props);
        this.hasCSS = true;
        this.shoppingService = this.elementPage.createService(ShoppingService);
        this.imageService = this.elementPage.createService(ImageService);

        this.state = {
            productsCount: 1,
            productSourceType: 'category', productNameLines: 'singleLine',
            showFields: 'independent', imageSize: 'small',
            listType: 'doubleColumn'
        };
    }
    get persistentMembers(): (keyof State)[] {
        return [
            'productSourceType', 'productsCount', 'categoryId', 'productIds',
            'listType', 'displayType', 'imageSize', 'productNameLines',
            'showFields', 'productTemplate'
        ]
    }

    async products(): Promise<Product[]> {
        var products: Product[];
        if (this.state.productSourceType == 'category')
            products = await this.shoppingService.productsByCategory(this.state.productsCount, this.state.categoryId);
        else {
            products = await this.shoppingService.productsByIds(this.state.productIds);
        }

        return products;
    }

    async componentWillReceiveProps(props) {
        super.componentWillReceiveProps(props);

        let products = await this.products();
        this.setState({ products });
    }

    _render(h: any): JSX.Element | JSX.Element[] {

        let { productNameLines } = this.state;

        return <DataList {...{
            className: "product-list-control",
            loadData: () => this.products()
        }} >
            <DataListContext.Consumer>
                {args => {
                    let p = args.item as Product;
                    let offShelve = p.OffShelve;
                    let stock = p.Stock;
                    let offlineText = offShelve ? '已下架' : stock <= 0 ? '已售罄' : '';
                    let price = "￥" + p.Price.toFixed(2);
                    let titleClassName = productNameLines == 'singleLine' ? 'name single-line' : 'name double-line';
                    let name = p.Name;
                    return <div className="product double col-xs-6">
                        <div className="btn-link">
                            <img className="product-image" src={this.imageService.imageSource(p.ImagePath, 120, 120)} />
                            {offlineText ? <div className="product-image-text">
                                {offlineText}
                            </div> : null}
                        </div>
                        <div className={`${titleClassName} btn-link`}>{name}</div>
                        <div className="price-bar">
                            <span className="pull-left">
                                {price}
                            </span>
                            <div className="product-count">
                            </div>
                        </div>
                    </div>
                }}
            </DataListContext.Consumer>
        </DataList>
    }
}

interface ProductListProps {
    productSourceType: State["productSourceType"],
    shoppingService: ShoppingService,
    productsCount?: number,
    categoryId?: string,
    productIds?: string[],
}
interface ProductListState {
    items: Product[],
}

// class ProductList extends React.Component<ProductListProps, ProductListState> {
//     constructor(props) {
//         super(props);

//         this.state = { items: null };
//     }
//     async products(props: ProductListProps): Promise<Product[]> {
//         var products: Product[];
//         if (props.productSourceType == 'category')
//             products = await this.props.shoppingService.productsByCategory(props.productsCount, props.categoryId);
//         else {
//             products = await this.props.shoppingService.productsByIds(props.productIds);
//         }

//         return products;
//     }
//     async componentWillReceiveProps(props: ProductListProps) {
//         let items = await this.products(props);
//         this.setState({ items })
//     }

//     render() {
//         let products = this.state.items || [];
//         return <div className="product-list-control">
//             {products.length > 0 ? products.map(p => {
//                 let offShelve = p.OffShelve;
//                 let stock = p.Stock;
//                 let offlineText = offShelve ? '已下架' : stock <= 0 ? '已售罄' : '';
//                 let price = "￥" + p.Price.toFixed(2);
//                 return <div className="product double col-xs-6">
//                     <div className="btn-link">
//                         <img className="product-image" src="{{image}}" />
//                         {offlineText ? <div className="product-image-text">
//                             {offlineText}
//                         </div> : null}
//                     </div>
//                     <div className="price-bar">
//                         <span className="pull-left">
//                             {price}
//                         </span>
//                         <div className="product-count">
//                         </div>
//                     </div>
//                 </div>
//             }) : <div>暂无可展示的商品</div>}
//         </div>
//     }
// }
